import React, { FC, memo, useCallback, useState } from 'react';
import { List, InputItem, Button, Toast } from 'antd-mobile';
import { createForm, FormValidateRule } from 'rc-form';
import { Link, history } from 'umi';
import { urlGet } from 'project-libs';
import { IRcFormProps } from '@/interface';
import { fetchLogin } from '@/api/user';

import './index.less';

const Login: FC<IRcFormProps> = props => {
  const { getFieldProps, getFieldError, validateFields } = props.form;
  const [btnLoading, setBtnLoading] = useState(false);

  const validateAccount = (
    rule: FormValidateRule,
    value: any,
    callback: (error?: any) => void,
  ) => {
    if (value && value.length > 4) {
      callback();
    } else {
      callback(new Error('账号长度不能小于4个字符'));
    }
  };

  const errorTips = useCallback((type: string) => {
    Toast.info(getFieldError(type).join('、'));
  }, []);

  const handleLogin = useCallback(() => {
    validateFields(async (err, val) => {
      if (!err) {
        setBtnLoading(true);
        const {
          data: { token, username },
          errorCode,
        } = await fetchLogin(val);
        setBtnLoading(false);
        if (errorCode === 0) {
          setTimeout(() => {
            Toast.success('登录成功');
          });
          localStorage.setItem('token', token);
          localStorage.setItem('username', username);

          setTimeout(() => {
            history.push(
              urlGet('from')
                ? decodeURIComponent(urlGet('from') as string)
                : '/',
            );
          }, 1600);
        }
      }
    });
  }, [setBtnLoading]);

  return (
    <div className="login-page-wrap">
      <form>
        <List renderHeader={() => '用户登录'}>
          <InputItem
            {...getFieldProps('username', {
              rules: [
                { required: true, message: '账号不能为空' },
                { validator: validateAccount },
              ],
            })}
            clear
            error={!!getFieldError('username')}
            onErrorClick={() => errorTips('username')}
            placeholder="请输入账号"
          >
            <span style={{ letterSpacing: '34px' }}>账号</span>
          </InputItem>
          <InputItem
            {...getFieldProps('password', {
              rules: [{ required: true, message: '密码不能为空' }],
            })}
            error={!!getFieldError('password')}
            onErrorClick={() => errorTips('password')}
            placeholder="请输入密码"
            type="password"
          >
            <span style={{ letterSpacing: '34px' }}>密码</span>
          </InputItem>
          <List.Item>
            <Button type="warning" onClick={handleLogin} loading={btnLoading}>
              登录
            </Button>
            <Link className="register" to="/register">
              没有账户，去注册
            </Link>
          </List.Item>
        </List>
      </form>
    </div>
  );
};

export default createForm<IRcFormProps>()(memo(Login));
